<script lang="ts">
import { onMounted, defineComponent, ref, reactive, toRefs, computed } from 'vue';
import { userService } from '../../../api/user';
import { Table, message } from 'ant-design-vue';
import type { Dayjs } from 'dayjs';
import zhCN from 'ant-design-vue/es/locale/zh_CN';
let userJSON=localStorage.getItem("user")
//@ts-ignore
let userobj=JSON.parse(userJSON)

const reportList = async() => {
  const response = await userService.reportList()
  state.data = response.data
}
const state = reactive({
  data:[], imageData:[]
})
const columns = [
  {title:'报告号',dataIndex:'reportNo',key:'reportNo'},
  {title:'患者号',dataIndex:'userId',key:'userId',},
  {
    title:'患者姓名',dataIndex:'patientName',key:'patientName',
    customFilterDropdown: true,
    //@ts-ignore
    onFilter: (value, record) =>
      record.patientName.toString().includes(value),
      //@ts-ignore
      onFilterDropdownVisibleChange: visible => {
        if (visible) {
            setTimeout(() => {
              searchInput.value.focus();
            }, 100);
          }
      },
  },
  {title:'性别',dataIndex:'gender',key:'gender',},
  {title:'年龄',dataIndex:'age',key:'age',},
  {title:'疾病名称',dataIndex:'diseaseName',key:'diseaseName',},
  {
    title:'负责医生',dataIndex:'doctorName',key:'doctorName',
    customFilterDropdown: true,
    //@ts-ignore
    onFilter: (value, record) =>
      record.doctorName.toString().includes(value),
      //@ts-ignore
      onFilterDropdownVisibleChange: visible => {
        if (visible) {
            setTimeout(() => {
              searchInput.value.focus();
            }, 100);
          }
      },
  },
  {
    title:'完成时间',dataIndex:'createTime',key:'createTime',
    //@ts-ignore
    sorter: (a, b) => {return a.createTime>b.createTime? 1:-1},
    sortDirections: ['descend', 'ascend'],
  },
]
//查询筛选相关
const search = reactive({
  searchText:'',searchColumn:'',
});
const searchInput = ref();
//@ts-ignore
const handleSearch = (selectedKeys, confirm, dataIndex) => {
      confirm();
      search.searchText = selectedKeys[0];
      search.searchColumn = dataIndex;
};
//@ts-ignore
const handleReset = clearFilters => {
      clearFilters({ confirm: true });
      search.searchText = '';
};
//@ts-ignore  将时间戳转化为可视的时间
const timeDisplay = (timestamp) =>{
  const date = new Date(timestamp);
  return date.toLocaleString();
};

//@ts-ignore 获取选中行的报告号等信息
const selectInfo = (record) =>{
  display.reportNo=record.reportNo;
  display.userId=record.userId;
  display.patientName=record.patientName;
  display.gender=record.gender;
  display.age=record.age;
  display.diseaseName=record.diseaseName;
  display.doctorName=record.doctorName;
  display.createTime=record.createTime;
  console.log(display)

};
//获取报告中的其他信息
const getDiseaseInfo = async() => {
  const response = await userService.getDiseaseInfo(display.reportNo)
  display.imageType=response.data.imageType
  display.diseaseName=response.data.diseaseName
  display.checkIntro=response.data.checkIntro
  display.imageInfo=response.data.imageInfo
  display.diagnose=response.data.diagnose
}
//报告展示界面 元素
const display = reactive({
  reportNo:0n, userId:0n, patientName:'', gender:'', age:'',
  diseaseName:'', checkIntro:'', imageType:'', imageInfo:'', 
  diagnose:'', doctorId:userobj.id, doctorName:'', createTime:null, 
})
//根据报告号获取影像
const getReportImage = async() => {
  const response = await userService.getReportImage(display.reportNo)
  state.imageData = response.data
  //@ts-ignore
  //console.log(state.imageData)
}
const visibleDrawer = ref<boolean>(false);
const showDrawer = () => {
  visibleDrawer.value = true;
};
//判断是否为自己负责的病人
const disabled = computed(() => {
  console.log(!(display.doctorName==userobj.name))
  return !(display.doctorName==userobj.name);
});
//订正报告
const revise = async () => {
  console.log(display)
  if(display.diseaseName=="" || display.checkIntro=="" || display.imageInfo=="" || display.diagnose==""){
    message.warning('请完整填写报告相关信息！');
  }
  else{
    const response = await userService.updateReport(display)
    if(response.data.code==200){
      message.success(response.data.msg)
    }
    else{
      message.error(response.data.msg)
    }
  }
}

export default defineComponent({
  setup(){
    onMounted(() => {
      reportList()
    })
    return{
      zhCN, 
      columns, state, timeDisplay,
      ...toRefs(search), handleSearch, handleReset, searchInput,
      showDrawer, visibleDrawer,
      display, disabled, selectInfo, getDiseaseInfo, getReportImage,
      revise,
    };
  }
});
</script>

<template>
  <a-config-provider :locale="zhCN">
    <a-table class="table" :dataSource="state.data" :columns="columns" :pagination="false" :scroll="{ y: 320 }">
      <template #bodyCell="{ column, record, text }">
        <template v-if="column.key === 'reportNo'">
          <a @click="selectInfo(record); getDiseaseInfo(); getReportImage(); showDrawer();">
            {{ record.reportNo }}
          </a>
        </template>
        <template v-else-if="column.key === 'createTime'">
          {{ timeDisplay(record.createTime) }}
        </template>
        <span v-if="searchText && searchColumn === column.dataIndex">
          <template
            v-for="(fragment, i) in text
              .toString()
              .split(new RegExp(`(?<=${searchText})|(?=${searchText})`, 'i'))"
          >
            <mark
              v-if="fragment.toLowerCase() === searchText.toLowerCase()"
              :key="i"
              class="highlight"
            >
              {{ fragment }}
            </mark>
            <template v-else>{{ fragment }}</template>
          </template>
        </span>
      </template>

      <template
        #customFilterDropdown="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }"
      >
        <div style="padding: 8px">
          <a-input
            ref="searchInput"
            :placeholder="`输入${column.title}`"
            :value="selectedKeys[0]"
            style="width: 188px; margin-bottom: 8px; display: block"
            @change="e => setSelectedKeys(e.target.value ? [e.target.value] : [])"
            @pressEnter="handleSearch(selectedKeys, confirm, column.dataIndex)"
          />
          <a-button
            type="primary"
            size="small"
            style="width: 90px; margin-right: 8px"
            @click="handleSearch(selectedKeys, confirm, column.dataIndex)"
          >
            <template #icon><SearchOutlined /></template>
            查询
          </a-button>
          <a-button size="small" style="width: 90px" @click="handleReset(clearFilters)">
            清空
          </a-button>
        </div>
      </template>
      <template #customFilterIcon="{ filtered }">
        <search-outlined :style="{ color: filtered ? '#108ee9' : undefined }" />
      </template>    
    </a-table>
  </a-config-provider>

  <a-drawer
    v-model:visible="visibleDrawer"
    class="drawer"
    title="影像与报告"
    placement="left"
    width="500px"
  >
    <a-descriptions class="basicInfo">
      <a-descriptions-item label="报告号">{{ display.reportNo }}</a-descriptions-item>
      <a-descriptions-item label="患者姓名">{{ display.patientName }}</a-descriptions-item>
      <a-descriptions-item label="性别">{{ display.gender }}</a-descriptions-item>
      <a-descriptions-item label="年龄">{{ display.age }}</a-descriptions-item>
      <a-descriptions-item label="影像类型">{{ display.imageType }}</a-descriptions-item>
      <a-descriptions-item label="负责医生">{{ display.doctorName  }}</a-descriptions-item>
    </a-descriptions>
    <a-from class="report" :model="display" name="report" :label-col="{ span: 8}" :wrapper-col="{ span: 16}">
      <a-form-item label="疾病名称" name="diseaseName" style="position:absolute; left:300px; top:230px">
        <a-input v-model:value="display.diseaseName" style="width:150px;" :disabled="disabled"/>
      </a-form-item>
      <a-form-item label="检查部位" name="checkIntro" style="position:absolute; left:300px; top:300px">
        <a-input v-model:value="display.checkIntro" style="width:150px;" :disabled="disabled"/>
      </a-form-item>
      <a-form-item label="影像所见信息" name="imageInfo" style="position:relative; top:300px">
        <a-textarea v-model:value="display.imageInfo" style="width: 285px;" :disabled="disabled"/>
      </a-form-item>
      <a-form-item label="影像学诊断" name="diagnose" style="position:relative; top:300px">
        <a-textarea v-model:value="display.diagnose" style="width: 300px;" :disabled="disabled"/>
      </a-form-item>
      <a-form-item>
        <a-button type="primary" html-type="submit" style="position:absolute; top:243px; left:400px; z-index:99;" :disabled="disabled" @click="revise">订正</a-button>
      </a-form-item>
    </a-from>
    <a-card title="患者影像" style="position:absolute; top:180px; width:260px; height:260px; overflow-y:auto; border:2px solid darkgray; border-radius:5px;">
      <a-image-preview-group>
        <div v-for="(item, index) in state.imageData" :key="index">
          <a-image :width="200" :src=item.image />
        </div>
      </a-image-preview-group>
    </a-card>
  </a-drawer>
</template>

<style scoped>
  .table{
    position: absolute;
    top: 120px;
    left: left;
    width: 80%;
  }
  .basicInfo{
    border-bottom: 2px dotted darkgray;
  }
</style>